package com.test.io.bio.server;

import com.test.io.bio.executor.ExecutorPool;
import com.test.io.bio.task.ListenerTask;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;

/**
 * describe:BIO模型服务端
 *
 * @author lianying
 * @date 2020/01/21
 */
public class BioServer {
    /**
     * 端口
     */
    private int port;
    /**
     * 状态锁
     */
    private ServerSocket serverSocket = null;

    public BioServer(int port) {
        this.port = port;
    }

    /**
     * 启动服务
     */
    public void start() {
        if (serverSocket == null) {
            try {
                serverSocket = new ServerSocket(port);
            } catch (IOException e) {
                System.out.println("服务启动失败");
                return;
            }
        }
        toListen();
    }

    /**
     * 监听连接
     */
    private void toListen() {
        try {
            while (true) {
                ExecutorPool.getInstance().execute(new ListenerTask(serverSocket.accept()));
            }
        } catch (IOException e) {
            System.out.println("监听服务失败");
            return;
        }
    }
}
